<?php

namespace App\Console\Commands;

use App\Dao\UsersDao;
use App\Services\Logger;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class userSpreads extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user_spread_tuan';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '用户团队同步';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        DB::update("update u_users SET spread_ids = ',' WHERE spread_ids IS NULL");
        $lists = UsersDao::builder_query()->where('spread_id','>',0)->where('is_spread_status',0);
        if($lists->exists()){
            Logger::user_spread_info('========>各种用户');
            $lists = $lists->orderByDesc('created_at')->get()->toArray();
            foreach ($lists as $value){
                $spread_id = $value['spread_id'];
                while (true){
                    if($spread_id == 0){
                        break;
                    }
                    $user_spread_info = UsersDao::builder_query([
                        'user_id'=>$spread_id
                    ])->first()->toArray();

                    if(in_array($value['user_id'],explode(',',$user_spread_info['spread_ids']))){
                        break;
                    }

                    UsersDao::builder_query([
                        'user_id'=>$spread_id
                    ])->update(['spread_ids'=>$user_spread_info['spread_ids'].$value['user_id'].',']);
                    $spread_id = $user_spread_info['spread_id'];
                }
            }




        }else{
            Logger::user_spread_info('========>暂无新用户');
        }
        DB::update("update u_users SET is_spread_status = 1 WHERE is_spread_status = 0");

    }
}
